import React, { useState, useEffect, useRef } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  InputNumber,
  message,
  Popconfirm,
  Card,
  Space,
  Divider,
  DatePicker
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined
} from '@ant-design/icons';
import {
  addApi,
  deleteApi,
  selectListApi,
  updateApi
} from './services';
import dayjs from 'dayjs';
import PageContent from '@/layout/pageContent';
import PageFooter from '@/layout/pageFooter';
const { RangePicker } = DatePicker;

const { Column } = Table;

interface Category {
  id: number;
  name: string;
  slug: string;
  comment?: string;
  createdAt: string;
  updatedAt: string;
  sortOrder?: number;
}

const Page: React.FC = () => {
  const [data, setData] = useState<Category[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchForm] = Form.useForm();
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [currentItem, setCurrentItem] = useState<Category | null>(null);
  const [searchParams, setSearchParams] = useState<any>({
    orderBy: "id desc"

  });

  useEffect(() => {
    fetchData();
  }, [pagination.current, pagination.pageSize, searchParams]);

  const fetchData = async () => {
    setLoading(true);
    try {
      const { data: res } = await selectListApi({
        page: pagination.current,
        pageSize: pagination.pageSize,

        ...searchParams
      });

      setData(res.list || []);
      setPagination({
        ...pagination,
        total: res.total || 0,
      });
    } catch (error) {
      message.error('获取分类列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleTableChange = (pagination: any) => {
    setPagination(pagination);
  };

  const handleSearch = (values: any) => {
    const params = {
    ...values,
      ...(values.date ? {
        fromDate: values.date[0],
        toDate: values.date[1]
      } : {})
    };
    delete params.date;
    setSearchParams({ ...searchParams, ...params });
    setPagination({ ...pagination, current: 1 });
  };

  const handleResetSearch = () => {
    searchForm.resetFields();
    setSearchParams({});
    setPagination({ ...pagination, current: 1 });
  };

  const handleDelete = async (id: number) => {
    try {
      const res = await deleteApi(id);
      if (res.code === 200) {
        message.success('删除成功');
        fetchData();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleEdit = (record: Category) => {
    setCurrentItem(record);
    form.setFieldsValue({
      ...record,
      createdAt: record.createdAt ? dayjs(record.createdAt) : undefined,
      updatedAt: record.updatedAt ? dayjs(record.updatedAt) : undefined,
    });
    setModalVisible(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const hide = message.loading('提交中...');

      const submitFn = currentItem ? updateApi : addApi;
      const submitData = currentItem
        ? { ...values, id: currentItem.id }
        : values;

      const res = await submitFn(submitData);
      hide();

      if (res.code === 200) {
        message.success(currentItem ? '更新成功' : '创建成功');
        setModalVisible(false);
        setCurrentItem(null);
        fetchData();
        return true;
      }
      return false;
    } catch (error) {
      console.error('提交失败:', error);
      return false;
    }
  };

  return (
    <>
      <PageContent title="文章分类管理">
        {/* 搜索表单 */}
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 16 }}
        >
          <Form.Item name="date" label="日期范围">
            <RangePicker />
          </Form.Item>
          <Form.Item name="name" label="名称">
            <Input placeholder="请输入分类名称" />
          </Form.Item>
          <Form.Item name="slug" label="别名">
            <Input placeholder="请输入分类别名" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                icon={<SearchOutlined />}
              >
                搜索
              </Button>
              <Button onClick={handleResetSearch}>
                重置
              </Button>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => {
                  setCurrentItem(null);
                  form.resetFields();
                  setModalVisible(true);
                }}
              >
                新建分类
              </Button>
            </Space>
          </Form.Item>
        </Form>

        {/* 数据表格 */}
        <Table<Category>
          size="small"
          rowKey="id"
          columns={[
            {
              title: '名称',
              dataIndex: 'name',
              sorter: true,
            },
            {
              title: '别名',
              dataIndex: 'slug',
              sorter: true,
            },
            {
              title: '描述',
              dataIndex: 'comment',
            },
            // {
            //   title: '排序',
            //   dataIndex: 'sortOrder',
            //   sorter: true,
            // },
            {
              title: '创建时间',
              dataIndex: 'createdAt',
              render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '-',
              sorter: true,
            },
            {
              title: '更新时间',
              dataIndex: 'updatedAt',
              render: (text) => text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '-',
              sorter: true,
            },
            {
              title: '操作',
              key: 'action',
              render: (_, record) => (
                <Space size="middle">
                  <Button
                    type="link"
                    icon={<EditOutlined />}
                    onClick={() => handleEdit(record)}
                  />
                  <Popconfirm
                    title="确定要删除这个分类吗？"
                    onConfirm={() => handleDelete(record.id)}
                  >
                    <Button
                      type="link"
                      danger
                      icon={<DeleteOutlined />}
                    />
                  </Popconfirm>
                </Space>
              ),
            },
          ]}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
        />

        {/* 新增/编辑模态框 */}
        <Modal
          title={currentItem ? '编辑分类' : '新建分类'}
          open={modalVisible}
          onOk={handleSubmit}
          onCancel={() => {
            setModalVisible(false);
            setCurrentItem(null);
          }}
          confirmLoading={loading}
          width={600}
          destroyOnClose
        >
          <Form
            form={form}
            layout="vertical"
            initialValues={{
              sortOrder: 0
            }}
          >
            <Form.Item
              label="名称"
              name="name"
              rules={[{ required: true, message: '请输入分类名称' }]}
            >
              <Input placeholder="请输入分类名称" />
            </Form.Item>

            <Form.Item
              label="别名"
              name="slug"
              rules={[
                { required: true, message: '请输入分类别名' },
                {
                  pattern: /^[a-z0-9-]+$/,
                  message: '只能包含小写字母、数字和连字符(-)'
                }
              ]}
            >
              <Input placeholder="例如: tech-news" />
            </Form.Item>

            <Form.Item
              label="描述"
              name="comment"
            >
              <Input.TextArea rows={3} />
            </Form.Item>
          </Form>
        </Modal>
      </PageContent>
      <PageFooter>
        1
      </PageFooter>

    </>
  );
};

export default Page;